package com.zimi.file.controller;

import com.zimi.file.exception.InvalidExtensionException;
import com.zimi.file.model.SysFile;
import com.zimi.file.service.FileInfoService;
import com.zimi.util.FileUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Slf4j
@Api("文件")
@RestController
@RequestMapping(value = "file")
public class FileApi {


    private final FileInfoService fileInfoService;

    @Autowired
    public FileApi(FileInfoService fileInfoService) {
        this.fileInfoService = fileInfoService;
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return
     */
    @PostMapping("upload")
    public Object uploadFile(@RequestParam("file") MultipartFile file) {
        // 判断文件是否为空
        if (file.isEmpty()) {
            return "文件不能为空";
        }
        try {
            return fileInfoService.upload(file);
        } catch (InvalidExtensionException e) {
            return "upload error InvalidExtensionException";
        }
    }

    //多文件上传
    @PostMapping("uploads")
    @ResponseBody
    public Object handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    return fileInfoService.upload(file);
                } catch (Exception e) {
                    return "You failed to upload " + i + " => "
                            + e.getMessage();
                }
            } else {
                return "You failed to upload " + i
                        + " because the file was empty.";
            }
        }
        return "upload successful";
    }

    /**
     * 文件下载
     *
     * @param id
     * @param res
     */
    @GetMapping(value = "download/{id}")
    public void downloadFile(@PathVariable("id") Integer id, HttpServletResponse res) {
        try {
            fileInfoService.downloadFile(id, res);
        } catch (InvalidExtensionException ignored) {
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件查看
     */
    @GetMapping(value = "view/{id}")
    public ResponseEntity<InputStreamResource> view(@PathVariable("id") Integer id) {
        SysFile sysFile = null;
        try {
            sysFile = fileInfoService.viewFile(id);
        } catch (IOException ignored) {
        }
        return fileView(sysFile);
    }

    static ResponseEntity<InputStreamResource> fileView(SysFile sysFile) {
        if (sysFile == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        HttpHeaders header = new HttpHeaders();
        if (FileUtils.match(sysFile.getFileName(), "jpg", "jpeg", "png", "gif", "bmp", "tif")) {
            header.setContentType(MediaType.IMAGE_JPEG);
        } else if (FileUtils.match(sysFile.getFileName(), "html", "htm")) {
            header.setContentType(MediaType.TEXT_HTML);
        } else if (FileUtils.match(sysFile.getFileName(), "pdf")) {
            header.setContentType(MediaType.APPLICATION_PDF);
        } else {
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        }
        header.add("X-Filename", sysFile.getFileName());
        header.add("X-MD5", sysFile.getMd5());

        return new ResponseEntity<>(new InputStreamResource(sysFile.getContent()), header, HttpStatus.OK);
    }

    /**
     * 文件列表查询
     */
    @GetMapping(value = "list")
    public Object findList(Integer id) {
        try {
            return fileInfoService.findFileList(id);
        } catch (InvalidExtensionException e) {
            return e.toString();
        }
    }

    /**
     * @param id
     * @return
     */
    @GetMapping(value = "delete/{id}")
    public Object deleteFile(@PathVariable("id") Integer id) {
        try {
            return fileInfoService.deleteFile(id);
        } catch (InvalidExtensionException e) {
            return e.toString();
        }
    }

}
